<?php

namespace IDock\Insurance\CHAC\Request;

use IDock\Common\Tools\PBEWithMD5AndDES\PBEWithMD5AndDES;
use IDock\Http\RequestFormat;
use IDock\Insurance\CHAC\Response\HEPolicyDownloadResponse;
use IDock\Visitor\EPolicyDownloadVisitor;

class HNCEPolicyDownloadRequest extends AllCHACRequest
{
    protected $route = 'new/policy/download';

    protected $response = HEPolicyDownloadResponse::class;

    protected $urlTip = '非车保单下载';

    protected $format = RequestFormat::JSON;
    /**
     * @var  EPolicyDownloadVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        return [
            'partnerCode' => $this->visitor->argc['NCPartnerCode'],
            'policyNO' => self::getPolicyNo($this->visitor->policyNo)
        ];
    }

    public function build(): string
    {
        $data = $this->generate();

        return $this->gateway.'/'.$this->route . '/partnerCode/' . $data['partnerCode'].'/policyNO/'.$data['policyNO'];
    }

    private function getPolicyNo($policyNo): string
    {
        $password = $this->visitor->argc['NCCodeKey'] ?? '';

        $salt = substr(md5($password, true),0,8);


        $crypt = PBEWithMD5AndDES::encrypt($policyNo, $password, $salt, 20, 1);

        $ciphertext = substr($crypt,0,32);

        return urldecode(base64_encode(base64_encode($salt).$ciphertext));
    }
}
